package com.xltt.watchclient.module.service;

import android.app.Service;
import android.bluetooth.le.ScanCallback;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Messenger;

import com.xltt.watchclient.LogTool;
import com.xltt.watchclient.module.ScanManager;

public class DeviceService extends Service {
    HandlerThread handlerThread;
    Handler ServerHandler;
    Messenger ServerMessenger;
    ScanManager mScanManager;
    ConnectServer mConnectServer;
    BleController mBleController;
    static DeviceService instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        LogTool.d("onCreate()");
        handlerThread = new HandlerThread("ServerHandlerThread");
        handlerThread.start();
        mBleController = new BleController(this);
        ServerHandler = new Handler(handlerThread.getLooper(), mBleController);
        ServerMessenger = new Messenger(ServerHandler);
        mScanManager = new ScanManager(this);
        mConnectServer = new ConnectServer(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return ServerMessenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mBleController.stopScan();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        handlerThread.getLooper().quit();
        handlerThread = null;
        //蓝牙线程终止
        ServerHandler = null;
        ServerMessenger = null;
        super.onDestroy();
    }

    public boolean startScan(ScanCallback scanCallback) {
        return mScanManager.start(scanCallback);
    }

    public boolean stopScan(ScanCallback scanCallback) {
        return mScanManager.stop(scanCallback);
    }

    public boolean connectToClient(String addres) {
        return mConnectServer.connectToClient(addres);
    }
}
